package com.hmall.controller.back;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hdmall.business.common.annotation.AuthRequired;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hdmall.business.common.util.MD5Util;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.service.CustomerManage;
import com.hmall.service.PlanManageService;
import com.hmall.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;


@RestController
@RequestMapping("/manage/user")
@Api(value = "后台用户管理操作API", description = "后台用户管理类API说明")
public class UserManageController {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    private final
    SysUserMapper sysUserMapper;
    private final
    SysUserRoleMapper sysUserRoleMapper;
    private final
    SysRoleMapper sysRoleMapper;
    private final
    SysDeptCustomerMapper sysDeptCustomerMapper;
    private final
    SysUserDeptMapper sysUserDeptMapper;
    private final
    MallDealerMapper mallDealerMapper;
    private final
    SysDeptMapper sysDeptMapper;
    private final
    SysCustomerMapper sysCustomerMapper;
    private final
    SysUserTempMapper sysUserTempMapper;
    private final
    SysUserDealerMapper sysUserDealerMapper;
    private final
    MallProductPlanMapper mallProductPlanMapper;
    private final
    PlanManageService planManageService;
    private final
    SysDeptRelationMapper sysDeptRelationMapper;
    private final
    SysRoleMenuMapper sysRoleMenuMapper;
    private final
    SysRoleDeptMapper sysRoleDeptMapper;
    private final
    CustomerManage customerManage;
    private final
    SysUserExtraMapper sysUserExtraMapper;
    private final
    MallVirtualUserMapper mallVirtualUserMapper;
    private final
    SysUserCertificationMapper sysUserCertificationMapper;
    private final
    DictionMapper dictionMapper;

    private final
    JedisPool jedisPool;

    @Autowired
    public UserManageController(MallDealerMapper mallDealerMapper, SysUserMapper sysUserMapper, SysRoleDeptMapper sysRoleDeptMapper, SysUserRoleMapper sysUserRoleMapper, SysUserExtraMapper sysUserExtraMapper, SysRoleMapper sysRoleMapper, SysDeptCustomerMapper sysDeptCustomerMapper, SysUserDeptMapper sysUserDeptMapper, MallProductPlanMapper mallProductPlanMapper, SysRoleMenuMapper sysRoleMenuMapper, SysDeptMapper sysDeptMapper, MallVirtualUserMapper mallVirtualUserMapper, SysCustomerMapper sysCustomerMapper, PlanManageService planManageService, JedisPool jedisPool, SysDeptRelationMapper sysDeptRelationMapper, SysUserTempMapper sysUserTempMapper, CustomerManage customerManage, SysUserDealerMapper sysUserDealerMapper, SysUserCertificationMapper sysUserCertificationMapper, DictionMapper dictionMapper) {
        this.mallDealerMapper = mallDealerMapper;
        this.sysUserMapper = sysUserMapper;
        this.dictionMapper = dictionMapper;
        this.sysRoleDeptMapper = sysRoleDeptMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.sysUserExtraMapper = sysUserExtraMapper;
        this.sysRoleMapper = sysRoleMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.sysUserDeptMapper = sysUserDeptMapper;
        this.mallProductPlanMapper = mallProductPlanMapper;
        this.sysRoleMenuMapper = sysRoleMenuMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.mallVirtualUserMapper = mallVirtualUserMapper;
        this.sysCustomerMapper = sysCustomerMapper;
        this.planManageService = planManageService;
        this.jedisPool = jedisPool;
        this.sysDeptRelationMapper = sysDeptRelationMapper;
        this.sysUserTempMapper = sysUserTempMapper;
        this.customerManage = customerManage;
        this.sysUserDealerMapper = sysUserDealerMapper;
        this.sysUserCertificationMapper = sysUserCertificationMapper;
    }

    @GetMapping("GetWmsState")
    @ApiOperation(value = "获得仓库状态")
    public ServerResponse GetWmsState() {
        Diction diction = dictionMapper.selectByDictionKey("wmsSwitch");
        return ServerResponse.createBySuccess(diction);
    }

    @PostMapping("UpdateWmsState")
    @ApiOperation(value = "更改仓库状态")
    public ServerResponse UpdateWmsState(Integer dictionId, String value) {
        Diction diction = dictionMapper.selectByPrimaryKey(dictionId);
        if (diction == null) {
            return ServerResponse.createByErrorMessage("id错误");
        }
        diction.setValue(value);
        dictionMapper.updateByPrimaryKey(diction);
        return ServerResponse.createBySuccess("修改成功");
    }

    @AuthRequired
    @GetMapping("GetUserList")
    @ApiOperation(value = "跟单员列表")
    public ServerResponse<PageInfo<UserVo>> GetUserList(Integer dept_id,
                                                        @RequestParam(value = "pageNum", defaultValue = "1")
                                                                int pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "100")
                                                                int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<UserVo> userVoList = sysUserMapper.selectMyUser(dept_id);
        PageInfo<UserVo> pageResult = new PageInfo<>(userVoList);

        return ServerResponse.createBySuccess(pageResult);
    }

    @AuthRequired
    @PostMapping("CreatedUser")
    @ApiOperation(value = "创建跟单员")
    public ServerResponse CreatedUser(String username, String password,
                                      Integer dept_id, Integer role_id, String question, String phone) {
        System.out.println(username);
        System.out.println(password);
        System.out.println(dept_id);
        System.out.println(role_id);

        SysUser sysUser = sysUserMapper.selectByUserName(username);

        if (sysUser != null) {
            return ServerResponse.createByErrorMessage("用户已存在");
        }

        SysUser newSysUser = new SysUser();
        newSysUser.setUsername(username);
        newSysUser.setRealName(question);
        newSysUser.setPassword(ENCODER.encode(password));
        newSysUser.setDeptId(dept_id);

        Date date = new Date();
        newSysUser.setCreateTime(date);
        newSysUser.setQuestion(question);
        newSysUser.setPhone(phone);
        sysUserMapper.myInsert(newSysUser);
        sysUser = sysUserMapper.selectByUserName(username);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(role_id);
        sysUserRoleMapper.insert(sysUserRole);

        return ServerResponse.createBySuccess("创建成功");
    }

    @AuthRequired
    @DeleteMapping("deleteUser")
    @ApiOperation(value = "删除跟单员")
    public ServerResponse<String> deleteUser(Integer[] idList) {
        int user_id;

        for (Integer anIdList : idList) {
            user_id = anIdList;
            sysUserMapper.deleteByPrimaryKey(user_id);
            sysUserRoleMapper.deleteByUserId(user_id);
        }

        return ServerResponse.createBySuccess("删除成功");
    }

    @AuthRequired
    @GetMapping("searchUser")
    @ApiOperation(value = "搜索跟单员")
    public ServerResponse<PageInfo<UserVo>> searchUser(Integer dept_id, String search,
                                                       @RequestParam(value = "pageNum", defaultValue = "1")
                                                               int pageNum,
                                                       @RequestParam(value = "pageSize", defaultValue = "100")
                                                               int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<UserVo> userVoList = sysUserMapper.selectBySearch(dept_id, search);
        PageInfo<UserVo> pageResult = new PageInfo<>(userVoList);

        return ServerResponse.createBySuccess(pageResult);
    }

    @AuthRequired
    @PostMapping("EditUser")
    @ApiOperation(value = "保存跟单员信息")
    public ServerResponse EditUser(Integer user_id, String username,
                                   Integer role_id, String question, String phone) {
        Integer count = sysUserMapper.checkUsernameByUserId(username, user_id);

        if (count > 0) {
            return ServerResponse.createByErrorMessage("用户名已存在");
        }

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user_id);

        if (sysUser == null) {
            return ServerResponse.createByErrorMessage("不存在该用户");
        }

        sysUser.setUsername(username);
        sysUser.setPhone(phone);
        sysUser.setRealName(question);
        sysUserMapper.updateByPrimaryKey(sysUser);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user_id);
        sysUserRole.setRoleId(role_id);
        sysUserRoleMapper.updateStatus(user_id, role_id);

        return ServerResponse.createBySuccess("修改成功");
    }

    @AuthRequired
    @GetMapping("getMyRole")
    @ApiOperation(value = "获取办事处的权限")
    public ServerResponse<List<RoleVo>> getMyRole(Integer dept_id) {
        System.out.println(dept_id);

        List<RoleVo> list = sysRoleMapper.selectMyRole(dept_id);

        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @PostMapping("checkUserNameCanUse")
    @ApiOperation(value = "检验用户名是否可用")
    public ServerResponse checkUserNameCanUse(String username) {
        SysUser checkUser = sysUserMapper.selectByUserName(username);


        if (checkUser != null) {
            return ServerResponse.createByErrorMessage("用户名已存在");
        }

        return ServerResponse.createBySuccess("能够使用");
    }

    @AuthRequired
    @PostMapping("createdUserByCustomer")
    @ApiOperation(value = "根据客户创建用户")
    public ServerResponse createdUserByCustomer(String username,
                                                String password, Integer customer_id, String real_name) {
        SysUser sysUser = new SysUser();
        SysUser checkUser = sysUserMapper.selectByUserName(username);


        if (checkUser != null) {
            return ServerResponse.createByErrorMessage("用户名已存在");
        }

        Integer dept_id = sysDeptCustomerMapper.selectByCustomerId(customer_id);
        Integer dealer_id = mallDealerMapper.selectDealerId(dept_id);
        sysUser.setDealer_id(dealer_id);
        sysUser.setUsername(username);

        String md5Password = MD5Util.MD5EncodeUtf8(password);
        sysUser.setPassword(md5Password);
        sysUser.setPhone(username);
        sysUser.setQuestion(username);
        sysUser.setAvatar(
                "http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330401567.png?Expires=1857690395&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=9KAS%2FMn7D8buLbLkjdZKW9jX3Lc%3D");
        sysUser.setCreateTime(new Date());
        sysUser.setDelFlag("0");
        sysUser.setRealName(real_name);
        sysUserMapper.insert(sysUser);
        sysUser = sysUserMapper.selectByUserName(username);

        SysUserDept sysUserDept = new SysUserDept();
        sysUserDept.setDeptId(dept_id);
        sysUserDept.setUserId(sysUser.getUserId());
        sysUserDeptMapper.insert(sysUserDept);

        Integer user_id = sysUserMapper.selectIdByUsername(username);
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);
        SysUserRole sysUserRole = sysUserRoleMapper.selectRole(user_id);
        if (sysUserRole == null) {
            SysUserRole sysUserRole1 = new SysUserRole();
            sysUserRole1.setRoleId(3);
            sysUserRole1.setUserId(user_id);
            sysUserRoleMapper.insert(sysUserRole1);
        } else {
            int status = 3;
            sysUserRoleMapper.updateStatus(user_id, status);
        }
        SysUserTemp sysUserTemp = new SysUserTemp();
        sysUserTemp.setUserId(user_id);
        sysUserTemp.setStatus(3);
        sysUserTemp.setLinkmanName(sysCustomer.getLinkmanName());
        sysUserTemp.setCreateTime(new Date());
        sysUserTemp.setOpinion("通过");
        sysUserTemp.setType(9);
        sysUserTempMapper.insert(sysUserTemp);

        if (!(sysCustomer.getSalesmanId() == null)) {
            user_id = sysCustomerMapper.selectCustomerUserId(customer_id);
            if (user_id == null) {
                return ServerResponse.createByErrorMessage("该客户下没有用户");
            }
            Date date = new Date();
            List<MallProductPlan> list = mallProductPlanMapper.checkPlan(user_id, date);
            if (list.size() == 0) {
                //创建今年十二个月的生成计划
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                for (int i = 1; i <= 12; i++) {
                    calendar.set(Calendar.MONTH, i - 1);
                    System.out.println(calendar.getTime().toLocaleString());
                    planManageService.createPlan(customer_id, calendar.getTime());
                }
            } else {
                for (MallProductPlan mallProductPlan : list) {
                    mallProductPlan.setSaleUserId(sysCustomer.getSalesmanId());
                    mallProductPlanMapper.updateByPrimaryKey(mallProductPlan);
                }
            }
        }

        return ServerResponse.createBySuccess("添加成功");
    }

    @AuthRequired
    @DeleteMapping("deleteCustomerUser")
    @ApiOperation(value = "删除用户")
    public ServerResponse<String> deleteCustomerUser(Integer user_id) {
        sysUserMapper.deleteUser(user_id);
        sysUserDeptMapper.deleteByUserId(user_id);
        sysUserRoleMapper.deleteByUserId(user_id);
        return ServerResponse.createBySuccess("删除成功");
    }

    @AuthRequired
    @GetMapping("getDeptInfo")
    @ApiOperation(value = "获得部门信息")
    public ServerResponse<SysDept> getDeptInfo(Integer dept_id) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(dept_id);

        return ServerResponse.createBySuccess(sysDept);
    }

    @AuthRequired
    @GetMapping("getRoleIdByUserId")
    @ApiOperation(value = "根据user_id获得role_id")
    public SysRole getRoleIdByUserId(Integer user_id) {
        SysUserRole sysRole = sysUserRoleMapper.selectRole(user_id);

        return sysRoleMapper.selectByPrimaryKey(sysRole.getRoleId());
    }

    @AuthRequired
    @PostMapping("updateUser")
    @ApiOperation(value = "修改用户信息")
    public ServerResponse updateUser(Integer user_id, String avatar, String password, String newpassword1) {
        System.out.println(user_id);
        System.out.println(avatar);
        System.out.println(password);
        System.out.println(newpassword1);
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user_id);
        if (sysUser == null) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        if (ENCODER.matches(password, sysUser.getPassword())) {
            sysUser.setAvatar(avatar);
            sysUser.setPassword(ENCODER.encode(newpassword1));
            sysUserMapper.updateByPrimaryKey(sysUser);
            Jedis jedis = jedisPool.getResource();
            jedis.del(sysUser.getUsername());
            jedis.close();
        } else {
            return ServerResponse.createByErrorMessage("密码错误");
        }
        return ServerResponse.createBySuccess("修改成功");
    }

    @AuthRequired
    @PostMapping("addDealer")
    @ApiOperation(value = "添加办事处")
    public ServerResponse<String> addDealer(String name) {
        Integer dept_id;
        try {
            dept_id = sysDeptMapper.selectIdByName(name);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("部门已存在");
        }
        MallDealer mallDealer = new MallDealer();
        mallDealer.setDeptId(dept_id);
        mallDealer.setDealerName(name);
        mallDealerMapper.insert(mallDealer);
        return ServerResponse.createBySuccess("添加成功");
    }

    @AuthRequired
    @GetMapping("getGenDanList")
    @ApiOperation(value = "跟单员列表")
    public ServerResponse<List<SysUser>> getGenDanList() {
        List<SysUser> sysUserList = sysUserMapper.selectGenDanList();
        return ServerResponse.createBySuccess(sysUserList);
    }

    @AuthRequired
    @GetMapping("getGenDanChecked")
    @ApiOperation(value = "获得跟单员绑定的办事处")
    public Integer[] getGenDanChecked(Integer user_id) {
        return sysUserDealerMapper.selectByUserId(user_id);
    }

    @AuthRequired
    @GetMapping("getDealerList")
    @ApiOperation(value = "获得办事处列表")
    public ServerResponse<List<TreeVo>> getDealerList(Integer user_id) {
        List<MallDealer> list = mallDealerMapper.selectAll();
        List<TreeVo> list1 = new ArrayList<>();
        List<Integer> list2 = sysUserDealerMapper.selectNotIn(user_id);
        for (MallDealer aList : list) {
            TreeVo treeVo = new TreeVo();
            treeVo.setId(aList.getDealerId());
            treeVo.setLabel(aList.getDealerName());
            if (list2.contains(aList.getDealerId())) {
                treeVo.setDisabled(true);
            } else {
                treeVo.setDisabled(false);
            }
            list1.add(treeVo);
        }
        return ServerResponse.createBySuccess(list1);
    }

    @AuthRequired
    @PostMapping("updateGenDanDealer")
    @ApiOperation(value = "更新办事处列表")
    public ServerResponse<String> updateGenDanDealer(Integer[] array, Integer user_id) {
        Integer[] checked = sysUserDealerMapper.selectByUserId(user_id);
        List<Integer> list1 = Arrays.asList(array);
        List<Integer> list2 = Arrays.asList(checked);
        //新增数据
        for (Integer aList1 : list1) {
            if (!list2.contains(aList1)) {
                SysUserDealer sysUserDealer = new SysUserDealer();
                sysUserDealer.setUserId(user_id);
                sysUserDealer.setDealerId(aList1);
                sysUserDealerMapper.insert(sysUserDealer);
            }
        }
        //删除数据
        for (Integer aList2 : list2) {
            if (!list1.contains(aList2)) {
                sysUserDealerMapper.deleteByDealerIdAndUserId(aList2, user_id);
            }
        }
        return ServerResponse.createBySuccess("修改成功");
    }

    @AuthRequired
    @GetMapping("getKefuList")
    @ApiOperation(value = "获得客服列表")
    public ServerResponse<List<RoleVo>> getKefuList() {
        List<RoleVo> list = sysUserMapper.getKefuList();
        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @GetMapping("getCheckedKefuList")
    @ApiOperation(value = "获得绑定客服列表")
    public ServerResponse<String[]> getCheckedKefuList(Integer customer_id) {
        String[] s = sysUserMapper.getCheckedKefuList(customer_id);
        return ServerResponse.createBySuccess(s);
    }

    @GetMapping("getVirtualData")
    @ApiOperation(value = "获得虚拟数据")
    public ServerResponse getVirtualData(Integer userId) {
        Map<String, Object> map = new HashMap<>();
        MallVirtualUser mallVirtualUser = mallVirtualUserMapper.selectByUserId(userId);
        if (mallVirtualUser == null) {
            return ServerResponse.createByErrorMessage("未创建虚拟数据");
        } else {
            SysUser sysUser = new SysUser();
            map.put("PC", mallVirtualUser);
            map.put("WeChat", sysUser);
            return ServerResponse.createBySuccess(map);
        }
    }

    @PostMapping("submitCertification")
    @ApiOperation(value = "实名认证申请")
    public ServerResponse submitCertification(Integer userId, String idNumber, String idFaceUrl, String idBackUrl) {
        Integer applyingCount = sysUserCertificationMapper.selectApplyingCount(userId);
        if (applyingCount >= 1) {
            return ServerResponse.createByErrorMessage("有正在申请中的实名认证，请等待审核");
        }
        Integer applySuccessCount = sysUserCertificationMapper.selectApplySuccessCount(userId);
        if (applySuccessCount >= 1) {
            return ServerResponse.createByErrorMessage("实名认证已通过，请勿重复提交");
        }
        SysUserCertification sysUserCertification = new SysUserCertification();
        sysUserCertification.setUserId(userId);
        sysUserCertification.setIdFaceUrl(idFaceUrl);
        sysUserCertification.setIdBackUrl(idBackUrl);
        sysUserCertification.setIdNumber(idNumber);
        sysUserCertification.setIsPass(0);
        sysUserCertificationMapper.insert(sysUserCertification);
        return ServerResponse.createBySuccess("提交成功，请等待审核");
    }

    @PostMapping("examCertification")
    @ApiOperation(value = "实名认证审核", notes = "isPass 1:通过 2:不通过")
    public ServerResponse examCertification(Integer id, Integer isPass) {
        SysUserCertification sysUserCertification = sysUserCertificationMapper.selectByPrimaryKey(id);
        sysUserCertification.setIsPass(isPass);
        sysUserCertificationMapper.updateByPrimaryKey(sysUserCertification);
        return ServerResponse.createBySuccess("审核成功");
    }

    @GetMapping("checkCertificationStatus")
    @ApiOperation(value = "检查实名认证情况", notes = "status 0:申请中 1:申请通过 2:申请不通过 3:未申请")
    public ServerResponse checkCertificationStatus(Integer userId) {
        certificationVo certificationVo = new certificationVo();
        Integer applyingCount = sysUserCertificationMapper.selectApplyingCount(userId);
        if (applyingCount >= 1) {
            certificationVo.setStatus(0);
            certificationVo.setMsg("实名认证申请中");
            return ServerResponse.createBySuccess(certificationVo);
        }
        Integer applySuccessCount = sysUserCertificationMapper.selectApplySuccessCount(userId);
        if (applySuccessCount >= 1) {
            certificationVo.setStatus(1);
            certificationVo.setMsg("实名认证已通过");
            return ServerResponse.createBySuccess(certificationVo);
        }
        Integer count = sysUserCertificationMapper.selectApplyCount(userId);
        if (count == 0) {
            certificationVo.setStatus(3);
            certificationVo.setMsg("实名认证未申请");
            return ServerResponse.createBySuccess(certificationVo);
        }
        SysUserCertification sysUserCertification = sysUserCertificationMapper.selectLastApply(userId);
        if (sysUserCertification.getIsPass() == 2) {
            certificationVo.setStatus(2);
            certificationVo.setMsg("实名认证未通过");
            return ServerResponse.createBySuccess(certificationVo);
        }
        return ServerResponse.createByErrorMessage("未知错误");
    }


    @PostMapping("createVirtualData")
    @ApiOperation(value = "创建虚拟数据")
    public ServerResponse createVirtualData(Integer userId) throws Exception {
        MallVirtualUser mallVirtualUser = mallVirtualUserMapper.selectByUserId(userId);
        if (mallVirtualUser != null) {
            return ServerResponse.createByErrorMessage("该用户已经创建了测试数据");
        }
        List<Integer> checkedOrder = new ArrayList<>();
//        for (int i=0;i<checkedOrders.length;i++){
//            switch (checkedOrders[i]){
//                case "创建审核中订单":
//                    checkedOrder.add(1);
//                    break;
//                case "创建已付款待发货订单":
//                    checkedOrder.add(2);
//                    break;
//                case "发货中订单":
//                    checkedOrder.add(3);
//                    break;
//                case "交易完成订单":
//                    checkedOrder.add(4);
//                    break;
//                case "已付款待发货":
//                    checkedOrder.add(5);
//                    break;
//            }
//        }
        for (int i = 0; i < 5; i++) {
            checkedOrder.add(i + 1);
        }
        int number = (int) (Math.random() * 9000) + 1000;
        String name = "演示办事处" + number;
        //创建dept
        SysDept sysDept = new SysDept();
        sysDept.setCreateTime(new Date());
        sysDept.setDelFlag("0");
        sysDept.setParentId(11);
        sysDept.setName(name);
        sysDeptMapper.insert(sysDept);
        sysDept = sysDeptMapper.selectByName(name);
        //增加部门关系表 作用未知
        SysDeptRelation sysDeptRelation = new SysDeptRelation();
        sysDeptRelation.setAncestor(sysDept.getDeptId());
        sysDeptRelation.setDescendant(sysDept.getDeptId());
        sysDeptRelationMapper.insert(sysDeptRelation);
        //增加办事处
        MallDealer mallDealer = new MallDealer();
        mallDealer.setDeptId(sysDept.getDeptId());
        mallDealer.setDealerName(name);
        mallDealerMapper.insert(mallDealer);
        mallDealer = mallDealerMapper.selectByName(name);
        //增加跟单员
        SysUser gendan = new SysUser();
        gendan.setUsername("gendan" + number);
        gendan.setPassword("$2a$10$MrJtAlNVTTR1h/PrQcUgyeJsSQNgygdm4zpvkB.fYyomJDgNiildq");
        gendan.setAvatar("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330401567.png?Expires=1857690395&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=9KAS%2FMn7D8buLbLkjdZKW9jX3Lc%3D");
        gendan.setDeptId(305);
        gendan.setCreateTime(new Date());
        gendan.setStatus(9);
        gendan.setRealName("gendan" + number);
        gendan.setDelFlag("0");
        sysUserMapper.insert(gendan);
        gendan = sysUserMapper.selectByUserName("gendan" + number);
        SysUserRole sysUserRole2 = new SysUserRole();
        sysUserRole2.setUserId(gendan.getUserId());
        sysUserRole2.setRoleId(89);
        sysUserRoleMapper.insert(sysUserRole2);
        //跟单员绑定办事处
        SysUserDealer sysUserDealer = new SysUserDealer();
        sysUserDealer.setUserId(gendan.getUserId());
        sysUserDealer.setDealerId(mallDealer.getDealerId());
        sysUserDealerMapper.insert(sysUserDealer);

        //创建办事处管理员权限
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(name + "管理员");
        sysRole.setRoleCode("ROLE_YANSHI" + number + "_ADMIN");
        sysRole.setRoleDesc(name + "管理员");
        sysRole.setCreateTime(new Date());
        sysRole.setDelFlag("0");
        sysRoleMapper.insert(sysRole);
        sysRole = sysRoleMapper.selectByName(name + "管理员");
        //绑定管理员权限
        Integer[] roleList = sysRoleMenuMapper.selectByRoleId(68);
        for (Integer aRoleList : roleList) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(sysRole.getRoleId());
            sysRoleMenu.setMenuId(aRoleList);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
        //sys_role_dept表
        SysRoleDept sysRoleDept = new SysRoleDept();
        sysRoleDept.setRoleId(sysRole.getRoleId());
        sysRoleDept.setDeptId(sysDept.getDeptId());
        sysRoleDeptMapper.insert(sysRoleDept);
        //创建管理员账号
        SysUser sysUser = new SysUser();
        sysUser.setUsername("yanshi" + number);
        sysUser.setPassword("$2a$10$MrJtAlNVTTR1h/PrQcUgyeJsSQNgygdm4zpvkB.fYyomJDgNiildq");
        sysUser.setAvatar("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330401567.png?Expires=1857690395&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=9KAS%2FMn7D8buLbLkjdZKW9jX3Lc%3D");
        sysUser.setDeptId(sysDept.getDeptId());
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(9);
        sysUser.setDelFlag("0");
        sysUser.setRealName("yanshi" + number);
        sysUserMapper.insert(sysUser);
        sysUser = sysUserMapper.selectByUserName("yanshi" + number);
        //sys_user_role表
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(sysRole.getRoleId());
        sysUserRoleMapper.insert(sysUserRole);
        //创建客户
        SysCustomerVo sysCustomerVo = new SysCustomerVo();
        sysCustomerVo.setBus_name("演示客户" + number);
        sysCustomerVo.setLinkman_name("演示用户" + number);
        sysCustomerVo.setLinkman_tel("1782685" + number);
        sysCustomerVo.setBus_person_name("演示客户" + number);
        sysCustomerVo.setBus_person_id("110101199003072252");
        sysCustomerVo.setBus_address("演示地址");
        sysCustomerVo.setCaptial("16800万元人民币");
        sysCustomerVo.setValid_period("2000-02-29 至 2025-02-28");
        sysCustomerVo.setBusiness("针织品、纺织服装(以上经营范围不含染色)、文具(不含印制)、工艺品(不含电镀)制造销售;日用百货批发;实业投资。");
        sysCustomerVo.setReg_num("91330782704574" + number);
        sysCustomerVo.setInvoice_title("演示公司" + number);
        sysCustomerVo.setInvoice_title_addr("演示地址");
        sysCustomerVo.setTax_num("91330782704574" + number);
        sysCustomerVo.setBank_name("中国工商银行");
        sysCustomerVo.setBank_number("623300000000");
        sysCustomerVo.setDept_id(sysDept.getDeptId());
        sysCustomerVo.setTax_cert_url("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330769851.png?Expires=1857690763&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=6V%2BPqVC3LPmtxsmg%2F20Ki0cd6Tg%3D");
        sysCustomerVo.setAuth_url("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330744058.png?Expires=1857690739&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=DluuJD8Fdy1HurzgE%2Fl8%2FfW40DI%3D");
        sysCustomerVo.setLicense_url("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330719636.jpg?Expires=1857690714&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=93wmi9llb09e7DrsVqM8pHE%2BKkE%3D");
        sysCustomerVo.setId_face_url("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330789177.jpg?Expires=1857690788&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=ySb4uyafFxBeQqKfLvZT2q7LP2I%3D");
        sysCustomerVo.setId_back_url("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1542330841142.png?Expires=1857690834&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=HDyZ%2FpyHfkLj7Yc4iUXMbYWS7kI%3D");
        customerManage.addCustomer(sysCustomerVo);
        Integer customer_id = sysCustomerMapper.selectCustomerByName(sysCustomerVo.getBus_name());
        customerManage.addUser(sysCustomerVo.getLinkman_tel(), "e10adc3949ba59abbe56e057f20f883e", customer_id, sysCustomerVo.getLinkman_name(), sysCustomerVo.getAuth_url(), sysCustomerVo.getLicense_url(), sysCustomerVo.getTax_cert_url(), sysCustomerVo.getId_face_url(), sysCustomerVo.getId_back_url());
        //绑定业务员
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);

        if (sysCustomer == null) {
            return ServerResponse.createByErrorMessage("客户不存在");
        }

        sysCustomer.setSalesmanId(sysUser.getUserId());
        sysCustomerMapper.updateByPrimaryKey(sysCustomer);

        //判断该客户是否创建了计划
        //获得该客户最早注册的用户
        Integer user_id = sysCustomerMapper.selectCustomerUserId(customer_id);
        if (user_id == null) {
            return ServerResponse.createByErrorMessage("该客户下没有用户");
        }
        Date date = new Date();
        List<MallProductPlan> list = mallProductPlanMapper.checkPlan(user_id, date);
        if (list.size() == 0) {
            //创建今年十二个月的生成计划
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            for (int i = 1; i <= 12; i++) {
                calendar.set(Calendar.MONTH, i - 1);
                System.out.println(calendar.getTime().toLocaleString());
                planManageService.createPlan(customer_id, calendar.getTime());
            }
        } else {
            for (MallProductPlan mallProductPlan : list) {
                mallProductPlan.setSaleUserId(sysUser.getUserId());
                mallProductPlanMapper.updateByPrimaryKey(mallProductPlan);
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("customerUserId", user_id.toString());
        map.put("salesmanUserId", sysUser.getUserId().toString());
        map.put("merchUserId", gendan.getUserId().toString());
//        map.put("typeList",checkedOrder.toString());
        String s = HttpClientUtil.doGetWithParam("http://47.98.171.71:9094/back/createTestData", map);
        System.out.println("*******************************");
        System.out.println(s);
        MallVirtualUser mallVirtualUser1 = new MallVirtualUser();
        mallVirtualUser1.setUserId(userId);
        mallVirtualUser1.setGendan(gendan.getUsername());
        mallVirtualUser1.setSalesman(sysUser.getUsername());
        mallVirtualUser1.setUsername(sysCustomerVo.getLinkman_tel());
        mallVirtualUserMapper.insert(mallVirtualUser1);
        Map<String, String> map2 = new HashMap<>();
        map2.put("gendan", gendan.getUsername());
        map2.put("salesman", sysUser.getUsername());
        map2.put("username", sysCustomerVo.getLinkman_tel());
        map2.put("password", "123456");
        return ServerResponse.createBySuccess(map2);
    }

    @AuthRequired
    @GetMapping("checkUser")
    @ApiOperation(value = "校验用户是否存在")
    public ServerResponse checkUser(String phone) {
        SysUserExtra sysUserExtra;
        try {
            sysUserExtra = sysUserExtraMapper.checkUser(phone);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("账号存在错误");
        }
        if (sysUserExtra == null) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        return ServerResponse.createBySuccess("用户存在");
    }

    @GetMapping("getUserDetail")
    @ApiOperation(value = "获得用户信息")
    public ServerResponse getUserDetail(String open_id) {
        Map<String, Object> resultObj = new HashMap<>();
        SysUserExtra sysUserExtra = sysUserExtraMapper.selectByWeChatOpenId(open_id);
        if (sysUserExtra == null) {
            return ServerResponse.createByErrorMessage("该微信号未绑定华鼎云商账号");
        }
        Integer customer_id = sysCustomerMapper.selectCustomerId(sysUserExtra.getUserId());
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(sysUserExtra.getUserId());
        if (customer_id == null) {
            resultObj.put("sysUser", sysUser);
            return ServerResponse.createBySuccess("资质未认证", resultObj);
        }
        SysCustomer sysCustomer = sysCustomerMapper.selectByPrimaryKey(customer_id);
        resultObj.put("sysCustomer", sysCustomer);
        resultObj.put("sysUser", sysUser);
        return ServerResponse.createBySuccess(resultObj);
    }

    @GetMapping("getMyUserOpenIdList")
    @ApiOperation(value = "获得我的用户的open_id")
    public ServerResponse getMyUserOpenIdList(Integer user_id) {
        String[] openIdList = sysUserExtraMapper.selectMyUserOpenIdList(user_id);
        if (openIdList.length == 0) {
            return ServerResponse.createByErrorMessage("该业务员没有微信绑定的客户");
        }
        return ServerResponse.createBySuccess(openIdList);
    }

    @GetMapping("getWeChatCustomerName")
    @ApiOperation(value = "微信端获得客户名称")
    public ServerResponse<String> getWeChatCustomerName(String open_id) {
        String customer_name = sysUserExtraMapper.selectCustomerName(open_id);
        return ServerResponse.createBySuccess(customer_name);
    }

    @AuthRequired
    @GetMapping("getBindingList")
    @ApiOperation(value = "获取多资质绑定列表")
    public ServerResponse<List<SysUserBinding>> getBindingList(String username, String real_name, String bus_name) {
        List<SysUserBinding> sysUserBindingList = sysUserMapper.selectBindingList(username, real_name, bus_name);
        return ServerResponse.createBySuccess(sysUserBindingList);
    }

    @AuthRequired
    @PostMapping("unbindingCustomer")
    @ApiOperation(value = "多资质解绑")
    public ServerResponse<String> unbindingCustomer(Integer user_id, Integer dept_id) {
        sysUserDeptMapper.deleteByUserIdAndDeptId(user_id, dept_id);
        sysUserTempMapper.deleteByUserId(user_id);
        return ServerResponse.createBySuccess("解绑成功");
    }

    @AuthRequired
    @PostMapping("bindingCustomer")
    @ApiOperation(value = "绑定资质")
    public ServerResponse bindingCustomer(String username, Integer customer_id) {
        SysUser sysUser = sysUserMapper.selectByUserName(username);
        if (sysUser == null) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        SysUserDept sysUserDept2 = sysUserDeptMapper.selectByUserId(sysUser.getUserId());
        if (sysUserDept2 == null) {
            return ServerResponse.createByErrorMessage("该手机号未进行过资质认证");
        }
        Integer dept_id = sysDeptCustomerMapper.selectByCustomerId(customer_id);
        Integer num = sysUserDeptMapper.checkBinding(username, dept_id);
        if (num != 0) {
            return ServerResponse.createByErrorMessage("该手机号已经绑定该公司");
        }
        String username2 = username + "-" + getRandomChar();
        SysUser sysUser2 = new SysUser();
        sysUser2.setUsername(username2);
        sysUser2.setPassword(sysUser.getPassword());
        sysUser2.setAvatar(sysUser.getAvatar());
        sysUser2.setQuestion(sysUser.getQuestion());
        sysUser2.setAnswer(sysUser.getAnswer());
        sysUser2.setCreateTime(new Date());
        sysUser2.setDelFlag(sysUser.getDelFlag());
        sysUser2.setStatus(sysUser.getStatus());
        sysUser2.setRealName(sysUser.getRealName());
        sysUser2.setDealer_id(sysUser.getDealer_id());
        sysUserMapper.insert(sysUser2);


        Integer userId = sysUserMapper.selectByUserName(username2).getUserId();
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByUserId(userId);
        if (sysUserTemp == null) {
            SysUserTemp sysUserTemp1 = new SysUserTemp();
            sysUserTemp1.setUserId(userId);
            sysUserTemp1.setStatus(3);
            sysUserTemp1.setOpinion("通过");
            sysUserTemp1.setType(9);
            sysUserTempMapper.insert(sysUserTemp1);
        } else {
            sysUserTemp.setUserId(userId);
            sysUserTemp.setStatus(3);
            sysUserTemp.setOpinion("通过");
            sysUserTemp.setType(9);
            sysUserTempMapper.updateByPrimaryKey(sysUserTemp);
        }

        Integer user_id = sysUserMapper.selectIdByUsername(username2);
        SysUserDept sysUserDept = new SysUserDept();
        sysUserDept.setDeptId(dept_id);
        sysUserDept.setUserId(user_id);
        sysUserDeptMapper.insert(sysUserDept);
        return ServerResponse.createBySuccess("创建成功");
    }


    private static String getRandomChar() {
        //生成随机字符串
        char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        Random random = new Random();
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            buffer.append(chr[random.nextInt(36)]);
        }
        return buffer.toString();
    }

    @GetMapping("generateShop")
    @ApiOperation(value = "generateShop")
    public ServerResponse generateShop() {

        return ServerResponse.createBySuccess();
    }

}
